#include <stdio.h>
#include <stdbool.h>

long get_long(long *);

bool bad_limits(long, long, long, long);

double sum_squares(long, long);

int main(void)
{
    const long MIN = -10000000L;
    const long MAX = 10000000L;

    long start, end;

    double answer;
    printf("This program computers the sum of the squares of "
           "integers in a range.\nThe lower bound should not "
           "be less than %+ld and \nthe upper bound should not"
           " be more than %+ld.\nEnter the limits (enter 0 for"
           " both limits to quit):\nlower limit: ",
           MIN,
           MAX);

    get_long(&start);
    printf("upper limit: ");
    get_long(&end);

    while (start != 0 || end != 0) {
        if (bad_limits(start, end, MIN, MAX))
            puts("Please try again!\n");

        else {
            answer = sum_squares(start, end);
            printf("The sum of the squares of the integers ");
            printf("from %ld to %ld is %g\n", start, end, answer);
        }

        printf("Enter the limits (enter 0 for both limits to quit):\n");
        printf("lower limit: ");
        get_long(&start);
        printf("upper limit: ");
        get_long(&end);
    }

    printf("Done.\n");

    return 0;
}

long get_long(long * input)
{
    int ch;

    while (scanf("%ld", input) != 1) {
        while ((ch = getchar()) != '\n')
            putchar(ch);

        printf(" is not an integer.\nPlease enter an "
               "integer value, such as 25, -178, or 3: ");
    }
    return *input;
}

double sum_squares(long start, long end)
{
    double sum;

    for (;start <= end; ++start) {
        sum += (double)start * (double)start;
    }

    return sum;
}

bool bad_limits(long start, long end, long low, long high)
{
    bool not_good = false;

    if (start > end) {
        printf("%ld isn't smaller than %ld.\n", start, end);
        not_good = true;
    }

    if (start < low) {
        printf("Values must be %ld or greater.\n", low);
        not_good = true;
    }

    if (start > high || end > high) {
        printf("Value must be %ld or less.\n", high);
        not_good = true;
    }

    return not_good;
}
